/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 *
 *
 *
 */
package rad.framework.seam;

import java.io.Serializable;

import org.jboss.seam.core.Events;

/**
 * @author boudyacho
 */
public class Pager implements Serializable {
	
	// TODO unit test
	
	public static final String EVENT = "Pager.pageChanged";

	private Integer pageSize = new Integer(20);

	protected int pageNumber = 0;

	protected Long objectCount = new Long(0);

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public Long getObjectCount() {
		return objectCount;
	}

	public void setObjectCount(Long objectCount) {
		this.objectCount = objectCount;
	}

	public Long getPageCount() {
		long count = getObjectCount();
		long size = getPageSize();
		long mod = count % size;
		return (count / size) + (mod > 0 ? 1 : 0);
	}

	public boolean isPreviousPage() {
		return pageNumber > 0;
	}

	public boolean isNextPage() {
		return getPageCount() > (getPageNumber() + 1);
	}
	
	public String findFirstPage() {
		pageNumber = 0;
		raiseEvent();
		return null;
	}

	public String findNextPage() {
		pageNumber++;
		raiseEvent();
		return null;
	}

	public String findPreviousPage() {
		pageNumber--;
		raiseEvent();
		return null;
	}

	public String findLastPage() {
		long count = getObjectCount();
		long size = getPageSize();
		long mod = count % size;
		pageNumber = new Long(count / size).intValue();
		if (mod == 0) {
			pageNumber--; // zero based
		}
		raiseEvent();
		return null;
	}
	
	protected void raiseEvent() {
        Events.instance().raiseEvent(EVENT);
	}
}
